package com.heima.gateway.filter;


import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @作者 itcast
 * @创建日期 2020/12/25 17:30
 **/
@Component
@Log4j2
@Order(0)
public class AuthorizeFilter implements GlobalFilter {
    List<String> urlList = Arrays.asList(
            "/v2/api-docs",
            "/login/in"
    );
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2. 判断当前的请求是否需要登录 如果不需要直接放行
        String path = request.getURI().getPath(); // 请求uri路径
        for (String url : urlList){
            if(path.contains(url)){
                return chain.filter(exchange); // chain 放行
            }
        }
        //3. 其它路径需要获取请求头中的token
        HttpHeaders headers = request.getHeaders();
        String jwtToken = headers.getFirst("token");
        //4. 判断token是否存在
        if (StringUtils.isEmpty(jwtToken)) {
            // 如果不存在,向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            //5. 如果令牌存在，解析jwt令牌 判断令牌是否合法
            Claims claims = AppJwtUtil.getClaimsBody(jwtToken);
            int result = AppJwtUtil.verifyToken(claims);
            if(result == 0 || result == -1){
                // 5.1 合法 则向header中重新设置userId
                Integer id = (int) claims.get("id");
                log.info("find userid;{} from uri: {}",id,request.getURI());
                // 重新设置token到header中
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("userId", String.valueOf(id));
                }).build();
                exchange = exchange.mutate().request(serverHttpRequest).build();
                return chain.filter(exchange);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //6.放行
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
}